package com.bknc.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class HttpEx extends Activity implements OnClickListener{

 public Button bSubmit;
 public Button bInsert;
 public TextView tvResult;
 public EditText edId;
 public EditText edShopName;
 public EditText edAddress;
 public EditText edTel1;
 public EditText edTel2;
 
//Hashmap for ListView
 ArrayList<HashMap<String, String>> sgolfList = new  ArrayList<HashMap<String, String>>();
 
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  initializeElements();
  
  
 }

 private void initializeElements() {
  // TODO Auto-generated method stub
  bSubmit  = (Button) findViewById(R.id.bSubmit);
  bInsert  = (Button) findViewById(R.id.bInsert);
  tvResult = (TextView) findViewById(R.id.tvResult);
  
  edId = (EditText) findViewById(R.id.edId);
  edShopName = (EditText) findViewById(R.id.edShopName);
  edAddress = (EditText) findViewById(R.id.edAddress);
  edTel1 = (EditText) findViewById(R.id.edTel1);
  edTel2 = (EditText) findViewById(R.id.edTel2);
		 
  
  
  bSubmit.setOnClickListener(this);
  bInsert.setOnClickListener(this);
 }

 public void onClick(View v) {
  // TODO Auto-generated method stub
   try{
       // check if you are connected or not
       if(isConnected()){
           tvResult.setBackgroundColor(0xFF00CC00);
           tvResult.setText("You are conncted");
       }
       else{
    	   tvResult.setText("You are NOT conncted");
       }
       
       switch (v.getId()) {
       case R.id.bSubmit:
    	   new MyAsyncTask().execute("abcdefghijklmn");
    	   break;
       case R.id.bInsert:
    	   new MyAsyncTask2().execute("abcdefghijklmn");
    	   break;
       }
	   
		

	   
    }catch(Exception e){
     Log.e("Error", e.getMessage());
     Toast.makeText(this, "Error: "+e, Toast.LENGTH_SHORT).show();
     //tts.speak("Sorry It seems that there is a problem in connection", TextToSpeech.QUEUE_FLUSH, null);
   }
   
 }

public boolean isConnected(){
       ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
           NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
           if (networkInfo != null && networkInfo.isConnected()) 
               return true;
           else
               return false;   
   }

 
 private class MyAsyncTask extends AsyncTask<String, Integer, String>{
	  
	 		@Override
	 		protected String doInBackground(String... params) {
	 			// TODO Auto-generated method stub
	 			return postData(params[0]);
	 		}
	  
	 		public String postData(String valueIWantToSend) {
	 			// Create a new HttpClient and Post Header
	 			HttpClient httpclient = new DefaultHttpClient();
	 			HttpEntity httpEntity = null;
	 			HttpResponse httpresponse = null;
	 			String result="";
	 			//HttpPost httppost = new HttpPost("http://192.168.11.3:8080/sgolf/SgolfTestSearchList.do");
	 			HttpPost httppost = new HttpPost("http://192.168.11.3:8080/sgolf/SgolfShopSearchList.do");
	  
	 			try {
	 				
					// Add your data
					List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	     			nameValuePairs.add(new BasicNameValuePair("id", edId.getText().toString()));
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
					
	 				// set delay time
	 				HttpParams params = httpclient.getParams();
	 				HttpConnectionParams.setConnectionTimeout(params, 3000);
	 				HttpConnectionParams.setSoTimeout(params, 3000);
	  
	 				// Execute HTTP Post Request
	 				httpresponse = httpclient.execute(httppost);
	 				
	 				// receive response as inputStream
	 				//inputStream = httpresponse.getEntity().getContent();
	 				
	 				// convert inputstream to string
	 				//if(inputStream != null)
	 				//	result = convertInputStreamToString(inputStream);
	 				//else
	 				//	result = "Did not work";
	 				
		 			httpEntity = httpresponse.getEntity();
		 			result = EntityUtils.toString(httpEntity);
	 			} catch (ClientProtocolException e) {
	 				// TODO Auto-generated catch block
	 			} catch (IOException e) {
	 				// TODO Auto-generated catch block
	 			}
 				return result;
	 		}
	 		
	 		@Override
	        protected void onPostExecute(String result) {
	 			//Toast.makeText(getBaseContext(), "REeived!"+result+";;", Toast.LENGTH_LONG).show();
/*
	 			JSONObject jsonObj = JSONObject.fromObject(JSONSerializer.toJSON(addr));
	 			JSONArray user = (JSONArray) jsonObj.get("user");
	 			JSONObject address = (JSONObject) user.get(0);
	 			System.out.println("name    : " + address.get("name"));
	 			System.out.println("address : " + address.get("address"));
	 			System.out.println("phone   : " + address.get("phone"));
	 	 
	 			System.out.println("--------- email info --------");
	 	 
	 			JSONObject emails = (JSONObject) address.get("emails");
	 			JSONArray email = (JSONArray) emails.get("email");
	 	 
	 			for (int i = 0; i < email.size(); i++) {
	 				JSONObject temp = (JSONObject) email.get(i);
	 				System.out.printf("id     :  %s     emailAddr  :  %s  \n",temp.get("id"), temp.get("emailAddr"));
	 			}  */
	 			
	 			
	 			// parse received data to json
	 		   Log.i("data received from server:",result);
	 		   
	 		   try {
	 			   JSONArray jArr = new JSONArray(result);
	 			   
	 			   
	 			// looping through All Contacts
                   for (int i = 0; i < jArr.length(); i++) {
                       JSONObject c = jArr.getJSONObject(i);
                        
                       String id = c.getString("id");
                       String shopname = c.getString("shop_name");
                       String address = c.getString("address");
                       String tel1 = c.getString("tel1");
                       String tel2 = c.getString("tel2");
                       String message = c.getString("message");

                       // tmp hashmap for single contact
                       HashMap<String, String> s = new HashMap<String, String>();

                       // adding each child node to HashMap key => value
                       s.put("id", id);
                       s.put("shop_name", shopname);
                       s.put("address", address);
                       s.put("tel1", tel1);
                       s.put("tel2", tel2);
                       s.put("message", message);

                       // adding contact to contact list
                       sgolfList.add(s);
                   }
                   HashMap<String, String> takeMap1 = (HashMap<String,String>)sgolfList.get(0);
                   edId.setText(takeMap1.get("id"));
                   edShopName.setText(takeMap1.get("shop_name"));
                   edAddress.setText(takeMap1.get("address"));
                   edTel1.setText(takeMap1.get("tel1"));
                   edTel2.setText(takeMap1.get("tel2"));
        		   Toast.makeText(getBaseContext(), takeMap1.get("message"), Toast.LENGTH_LONG).show();
   	            tvResult.setText(takeMap1.get("message"));
        		    
	 		   } catch (JSONException e) {
	 			  Toast.makeText(getBaseContext(), "JSONException;;"+e.getMessage(), Toast.LENGTH_LONG).show();
    			  e.printStackTrace();
	 		   }
	 			
	        }
	 		
			// convert inputstream to String
	 	    private String convertInputStreamToString(InputStream inputStream) throws IOException{
	 	        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
	 	        String line = "";
	 	        String result = "";
	 	        while((line = bufferedReader.readLine()) != null)
	 	            result += line;
	 	 
	 	        inputStream.close();
	 	        return result;
	 	 
	 	    }

	 	}
 
 private class MyAsyncTask2 extends AsyncTask<String, Integer, String>{
	  
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			return postData(params[0]);
		}

		public String postData(String valueIWantToSend) {
			// Create a new HttpClient and Post Header
			InputStream inputStream = null;
			HttpClient httpclient = new DefaultHttpClient();
			HttpEntity httpEntity = null;
			HttpResponse httpresponse = null;
			String result="";
			//HttpPost httppost = new HttpPost("http://192.168.11.3:8080/sgolf/SgolfTestSearchList.do");
			HttpPost httppost = new HttpPost("http://192.168.11.3:8080/sgolf/SgolfShopInsert.do");

			try {
				// Add your data
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     			nameValuePairs.add(new BasicNameValuePair("id", edId.getText().toString()));
     			nameValuePairs.add(new BasicNameValuePair("shop_name", edShopName.getText().toString()));
     			nameValuePairs.add(new BasicNameValuePair("address", edAddress.getText().toString()));
     			nameValuePairs.add(new BasicNameValuePair("tel1", edTel1.getText().toString()));
     			nameValuePairs.add(new BasicNameValuePair("tel2", edTel2.getText().toString()));
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
				
				// set delay time
				HttpParams params = httpclient.getParams();
				HttpConnectionParams.setConnectionTimeout(params, 3000);
				HttpConnectionParams.setSoTimeout(params, 3000);

				// Execute HTTP Post Request
				httpresponse = httpclient.execute(httppost);
				
				// receive response as inputStream
				//inputStream = httpresponse.getEntity().getContent();
				
				// convert inputstream to string
				//if(inputStream != null)
				//	result = convertInputStreamToString(inputStream);
				//else
				//	result = "Did not work";
				
	 			httpEntity = httpresponse.getEntity();
	 			result = EntityUtils.toString(httpEntity);
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}
			return result;
		}
		
		@Override
     protected void onPostExecute(String result) {
			//Toast.makeText(getBaseContext(), "REeived!"+result+";;", Toast.LENGTH_LONG).show();
			
			// parse received data to json
		   Log.i("data received from server:",result);
		   
		   try {
			   JSONArray jArr = new JSONArray(result);
			   
			   
			// looping through All Contacts
            for (int i = 0; i < jArr.length(); i++) {
                JSONObject c = jArr.getJSONObject(i);
                 
                String message = c.getString("message");

                // tmp hashmap for single contact
                HashMap<String, String> s = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                s.put("message", message);

                // adding contact to contact list
                sgolfList.add(s);
            }
            HashMap<String, String> takeMap1 = (HashMap<String,String>)sgolfList.get(0);
 		    Toast.makeText(getBaseContext(), takeMap1.get("message"), Toast.LENGTH_LONG).show();
            
		   } catch (JSONException e) {
			  Toast.makeText(getBaseContext(), "JSONException;;"+e.getMessage(), Toast.LENGTH_LONG).show();
			  e.printStackTrace();
		   }
			
         tvResult.setText(result);
     }
		
		// convert inputstream to String
	    private String convertInputStreamToString(InputStream inputStream) throws IOException{
	        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
	        String line = "";
	        String result = "";
	        while((line = bufferedReader.readLine()) != null)
	            result += line;
	 
	        inputStream.close();
	        return result;
	 
	    }

	} 
}






